<template>
  <div class="home">
    <div class="title-container">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.userName"
              placeholder="请输入姓名"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchClick"
            size="medium"
          >搜索
          </el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <perButton label="新建" type="primary" icon="el-icon-plus" size="medium" perms="PT_USER_ADD"
                   @click="handlerAccount"></perButton>
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
        >刷新
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%;"
        class="elTable"
      >
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <el-table-column prop="systemCode" label="系统编码" align="center"/>
        <el-table-column prop="systemName" label="系统名称" align="center"/>
        <el-table-column prop="userCode" label="用户编码" align="center"/>
        <el-table-column prop="userName" label="用户名称" align="center"/>
        <el-table-column label="系统类型" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.systemType=='pc'?'':'success'">
              {{ scope.row.systemType=='pc'?'pc网站':'app系统'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" align="center"/>
        <el-table-column prop="createByName" label="创建人" align="center"/>
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center">
          <template #default="{ row }">
            <perButton label="分配菜单" type="primary" size="mini" perms="PC_SYS_BULD_MENU"
                       @click="configMenu(row)"></perButton>
            <perButton label="编辑" type="warning" size="mini" perms="PT_USER_EDIT"
                       @click="handlerEdit(row)"></perButton>
            <perButton label="删除" type="danger" size="mini" perms="PT_USER_DEL"
                       @click="handlerDelete(row)"></perButton>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="getAccountData"
      />
    </el-card>

    <!-- 弹框 -->
    <yc-dialog ref="ycDialog" :dialogTitle="dialogTitle" :centerTitle="centerTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="newAccountFormRef"
            :rules="newAccountModelRules"
            :model="newAccountModel"
            label-width="100px"
          >
            <el-form-item label="系统类型" prop="systemType">
              <el-select v-model="newAccountModel.systemType" @change="selectChange" placeholder="请选择" class="w-100">
                <el-option
                  v-for="item in systemTypeDataList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="系统名称" prop="systemCode" v-if="newAccountModel.systemType == 'pc'">
              <el-select v-model="newAccountModel.systemCode" placeholder="请选择" class="w-100">
                <el-option
                  v-for="item in sysDataList"
                  :key="item.systemCode"
                  :label="item.systemName"
                  :value="item.systemCode">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="系统名称" prop="systemCode" v-else>
              <el-select v-model="newAccountModel.systemCode" placeholder="请选择" class="w-100">
                <el-option
                  v-for="item in appDataList"
                  :key="item.systemCode"
                  :label="item.systemName"
                  :value="item.systemCode">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户名称" prop="userCode">
              <el-select v-model="newAccountModel.userCode" placeholder="请选择" class="w-100">
                <el-option
                  v-for="item in userDataList"
                  :key="item.userCode"
                  :label="item.userName"
                  :value="item.userCode">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSave">确定</el-button>
        <el-button @click="$refs.ycDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>

    <!-- 分配菜单 -->
    <yc-dialog ref="configDialog" :dialogTitle="dialogTitle" :show-center="false">
      <template #content>
        <div class="dialog-content">
          <div v-for="(item, index) in menuDataList" :key="index" class="mb-3">
            <el-checkbox
              @change="(val) => handleCheckAllListChange(val, item)"
              :indeterminate="itemIndeterminate(item)"
              v-model="item.checkAll"
            >{{ item.menuName }}
            </el-checkbox>
            <el-checkbox-group
              v-model="checkedData"
              @change="handleCheckedCitiesChange"
              style="padding-left: 30px;">
              <el-checkbox
                class="mt-3"
                v-for="items in item.children"
                :key="items.menuCode"
                :label="items"
              >{{ items.menuName }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addOrUpdateLoading" @click="dialogSaveConfig">确定</el-button>
        <el-button @click="$refs.configDialog.dialogVisible = false">取消</el-button>
      </template>
    </yc-dialog>


    <!-- 封装操作后弹框 -->
    <global-message
      v-if="isGlobalMessageShow"
      @receive="receive"
      :message="message"
    />
  </div>
</template>

<script>
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"
  import {
    queryPage,
    insertByModel,
    updateByModel,
    deleteByModel,
    querySysList,
    queryProjectList,
    queryUserPcMenuList,
    saveUserPcMenu
  } from "@/api/systemBuilding/allocation"
  import { queryList } from "@/api/systemBuilding/appSystemBuilding"

  export default {
    components: {
      ycDialog,
      perButton
    },
    data() {
      return {
        projectCode: "",
        isGlobalMessageShow: false,
        message: "",
        tableData: [],
        tableItemObj: {},
        count: 0,
        pageIndex: 1,
        pageSize: 10,
        loading: false,

        searchModel: {
          userName: "",
          status: null //正常/停用状态（全部）
        },

        newAccountModel: {
          systemType: "pc",
          systemCode: "",
          userCode: "",
          id: 0
        },
        newAccountModelRules: {
          systemCode: [{required: true, message: "请输入系统名称", trigger: "change"}],
          userCode: [{required: true, message: "请输入系统名称", trigger: "change"}],
        },

        systemTypeDataList: [
          {value: "pc", label: "pc网站"},
          {value: "app", label: "app系统"},
        ],
        sysDataList: [],
        appDataList: [],
        userDataList: [],
        dialogTitle: "",
        centerTitle: "",


        menuDataList: [],
        checkedData: [],

        addOrUpdateLoading: false
      }
    },
    created() {
      this.projectCode = sessionStorage.getItem('projectCode')

      this.getAccountData()
    },
    methods: {
      /**
       * 获取表格方法
       */
      async getAccountData(tableInfo) {
        this.loading = true
        if (tableInfo) {
          const {userName, status} = tableInfo
          const {object} = await queryPage({
            projectCode: this.projectCode,
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
            userName,
            status
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        } else {
          const {object} = await queryPage({
            pageIndex: this.pageIndex,
            pageSize: this.pageSize,
          })
          this.tableData = object.data
          this.count = object.count
          this.loading = false
        }
      },
      pagination(pageItem) {
        this.getAccountData(pageItem.page, pageItem.limit)
      },
      // 搜索按钮
      async searchClick() {
        this.getAccountData(this.searchModel)
      },


      /**
       * 删除按钮
       */
      async handlerDelete({id}) {
        this.$confirm("确定删除此数据吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const {message, status} = await deleteByModel({id})
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },


      /**
       * 新建
       * */
      handlerAccount() {
        this.dialogTitle = "添加"
        this.centerTitle = "添加"

        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true

        Object.keys(this.newAccountModel).forEach((item) => {
          this.newAccountModel[item] = ""
        })
        this.newAccountModel.systemType = 'pc'

        this.querySysList()
        this.queryAppList()
        this.queryProjectList()
      },

      /**
       * 修改
       */
      handlerEdit(row) {
        this.dialogTitle = "编辑"
        this.centerTitle = "编辑"

        this.querySysList()
        this.queryAppList()
        this.queryProjectList()

        this.newAccountModel.id = row.id
        this.newAccountModel.systemType = row.systemType
        this.newAccountModel.systemCode = row.systemCode
        this.newAccountModel.userCode = row.userCode

        this.addOrUpdateLoading = false
        this.$refs.ycDialog.dialogVisible = true
      },

      selectChange(val) {
        this.newAccountModel.systemCode = ''
        // if (val == 'pc') {
        //   this.newAccountModel.systemCode
        // } else {
        //   this.newAccountModel.systemCode
        // }
      },

      async querySysList() {
        const {object} = await querySysList()
        this.sysDataList = object
      },
      async queryAppList() {
        const {object} = await queryList()
        this.appDataList = object
      },
      async queryProjectList() {
        const {object} = await queryProjectList()
        this.userDataList = object
      },
      dialogSave() {
        this.$refs.newAccountFormRef.validate(async (v) => {
          if (v) {
            this.addOrUpdateLoading = true
            if (this.newAccountModel.id) {
              const {message, status} = await updateByModel({...this.newAccountModel, projectCode: this.projectCode})
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            } else {
              const {message, status} = await insertByModel({...this.newAccountModel, projectCode: this.projectCode})
              if (status == 200) {
                this.getAccountData()
                this.$refs.ycDialog.dialogVisible = false
                this.$message.success(message)
              }
            }
            this.addOrUpdateLoading = false
          }
        })
      },

      // 分配菜单
      configMenu(row) {
        this.dialogTitle = "分配菜单"
        this.centerTitle = "分配菜单"
        this.tableItemObj = row
        this.addOrUpdateLoading = false
        this.$refs.configDialog.dialogVisible = true

        queryUserPcMenuList({
          userCode: row.userCode,
          systemCode: row.systemCode,
        }).then(res => {
          let tempArr = res.object || []
          this.menuDataList = tempArr
          this.checkedData = []
          // 添加checkAll是否全选
          this.menuDataList = this.menuDataList.map((v) => ({
            ...v,
            checkAll: false
          }))
          this.menuDataList.forEach((item) => {
            let newChild = item.children.filter((v) => {
              return v.messages == '1'
            })
            if (newChild.length == item.children.length) {
              item.checkAll = true
            } else {
              item.checkAll = false
            }
          })
          tempArr.forEach((item) => {
            item.children.forEach((v) => {
              if (v.messages == '1') {
                this.checkedData.push(v)
              }
            })
          })
        })
      },

      // 全选
      handleCheckAllListChange(val, item) {
        // 过滤掉没有选中的数据，item.child中不包含v时返回-1
        const filterArr = this.checkedData.filter((v) =>
          item.children.indexOf(v) == -1
        )
        this.checkedData = val ? filterArr.concat(item.children) : filterArr
      },
      // 是否全选
      itemIndeterminate(item) {
        return (
          item.children.some((v) => this.checkedData.indexOf(v) > -1) &&
          !item.children.every((v) => this.checkedData.indexOf(v) > -1)
        )
      },
      handleCheckedCitiesChange(val) {
        this.menuDataList.forEach((item) => {
          item.checkAll = true
          item.children.forEach((v) => {
            if (!this.checkedData.includes(v)) {
              item.checkAll = false
            }
          })
        })
      },

      dialogSaveConfig() {
        this.addOrUpdateLoading = true
        let arr = this.checkedData.map(item => {
          return item.menuCode
        })
        saveUserPcMenu({
          userCode: this.tableItemObj.userCode,
          systemCode: this.tableItemObj.systemCode,
          mapString1: arr.join('&')
        }).then(res => {
          if (res.status == 200) {
            this.$message.success(res.message)
            this.getAccountData()
            this.$refs.configDialog.dialogVisible = false
          }
          this.addOrUpdateLoading = false
        })
      },
      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {
          userName: "",
          status: null
        }
        this.getAccountData()
      },

      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      },
    }
  }
</script>

<style lang="scss" scoped>
  .status {
    display: inline-block;
    padding: 0 10px;
  }

  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      margin-left: 20px;
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }


  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    // justify-content: st-end;
    padding: 5px 20px;
  }
</style>
